<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 使用栅格布局: 每行宽24格，gutter设置列距，span设置每列占多少格 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getGoodsList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getGoodsList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="goAddGoodsPage">添加商品</el-button>
        </el-col>
      </el-row>

      <!-- 表格区域 -->
      <!-- 表格组件，表格数据从data中获取，每列数据从prop中获取 -->
      <el-table :data="goodsList" style="width: 100%" border stripe>
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="goods_name" label="商品名称" width="850px">
        </el-table-column>
        <el-table-column prop="goods_price" label="商品价格(元)">
        </el-table-column>
        <el-table-column prop="goods_weight" label="商品重量">
        </el-table-column>
        <el-table-column label="创建时间">
          <!-- 使用作用域插槽，自定义数据，然后使用过滤器，生成完整的时间 -->
          <template slot-scope="scope">
            {{ scope.row.add_time | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip
              effect="dark"
              content="编辑"
              placement="top"
              :enterable="false"
            >
              <el-button
                size="mini"
                type="primary"
                @click="showEditGoodsDialog(scope.row)"
                icon="el-icon-edit"
              ></el-button>
            </el-tooltip>

            <el-tooltip
              effect="dark"
              content="删除"
              placement="top"
              :enterable="false"
            >
              <el-button
                size="mini"
                type="danger"
                @click="handleDeleteGoods(scope.row)"
                icon="el-icon-delete"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 5, 10, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      >
      </el-pagination>
    </el-card>

    <!-- 编辑商品对话框 -->
    <el-dialog
      title="编辑商品"
      :visible.sync="editGoodsVisible"
      width="50%"
      @close="$refs.editGoodsFormRef.resetFields()"
    >
      <el-form
        :model="editGoodsForm"
        :rules="goodsFormRules"
        ref="editGoodsFormRef"
        label-width="100px"
      >
        <el-form-item label="商品名称" prop="goods_name">
          <el-input v-model="editGoodsForm.goods_name" disabled></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="goods_price">
          <el-input v-model="editGoodsForm.goods_price" disabled></el-input>
        </el-form-item>
        <el-form-item label="商品数量" prop="goods_number">
          <el-input v-model="editGoodsForm.goods_number" disabled></el-input>
        </el-form-item>
        <el-form-item label="商品重量" prop="goods_weight">
          <el-input v-model="editGoodsForm.goods_weight" disabled></el-input>
        </el-form-item>
      </el-form>

      <span style="color: red">注: api接口没有获取到分类的id，因此无法提交编辑数据</span>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editGoodsVisible = false">取 消</el-button>
        <el-button type="primary" @click="editGoods" disabled>确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Goods',
  data() {
    return {
      // 商品列表
      goodsList: [],
      // 控制对话框的显示与隐藏
      editGoodsVisible: false,
      // 查询商品的信息（默认查询全部商品）
      queryInfo: {
        query: '',
        // 当前页码
        pagenum: 1,
        // 每页显示的条数
        pagesize: 10,
      },
      // 商品的总数量
      total: 0,
        // 添加商品的表单规则
      goodsFormRules: {
        goods_name: [
          {
            required: true,
            message: '请输入商品的名称',
            trigger: ['blur', 'change'],
          }
        ],
        goods_price: [
          {
            required: true,
            message: '请输入商品的价格',
            trigger: ['blur', 'change'],
          }
        ],
        goods_weight: [
          {
            required: true,
            message: '请输入商品的重量',
            trigger: ['blur', 'change'],
          }
        ],
        goods_number: [
          {
            required: true,
            message: '请输入商品的数量',
            trigger: ['blur', 'change'],
          }
        ]
      },
      editGoodsForm: {}
    }
  },
  methods: {
    async getGoodsList() {
      const { data: res } = await this.$http.get('goods', {
        params: this.queryInfo,
      })
      if (res.meta.status !== 200)
        return this.$message.error('获取商品列表失败！！！')
      this.$message.success('获取商品列表成功！！！')
      this.goodsList = res.data.goods
      this.total = res.data.total
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      // 获取到新的 每页显示数量
      this.queryInfo.pagesize = newSize
      // 重新发送请求
      this.getGoodsList()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      // 获取到新的 页码值
      this.queryInfo.pagenum = newPage
      // 重新发送请求
      this.getGoodsList()
    },
    showEditGoodsDialog(params) {
      this.editGoodsForm = params
      this.editGoodsVisible = true
    },
    // 删除商品
    async handleDeleteGoods(row) {
      const confirmResult = await this.$confirm(
        `此操作将永久删除该商品 ${row.goods_name}, 是否继续?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除')
      const { data: ref } = await this.$http.delete('goods/' + row.goods_id)
      if (ref.meta.status !== 200)
        return this.$message.error(`商品 ${row.goods_name} 删除失败!`)
      this.$message.success(`商品 ${row.goods_name}} 删除成功!`)
      this.getGoodsList()
    },
    // 点击跳转到添加商品页面
    goAddGoodsPage() {
      // 跳转到指定的页面
      this.$router.push('/goods/add')
    },
    // 提交编辑商品
    editGoods() {
      this.$refs.editGoodsFormRef.validate(async (vaild) => {
        if (!vaild) return
        const { data: res } = await this.$http.put(
          'goods/' + this.editGoodsForm.goods_id,
          {
            goods_name: this.editGoodsForm.goods_name,
            goods_price: this.editGoodsForm.goods_price,
            goods_number: this.editGoodsForm.goods_number,
            goods_weight: this.editGoodsForm.goods_weight
          }
        )
        if (res.meta.status !== 200)
          return this.$message.error('修改商品信息失败')
        // 关闭对话框
        this.editUserVisible = false
        this.$message.success('修改商品信息成功')
        // 刷新表格
        this.getGoodsList()
      })
    }
  },
  created() {
    this.getGoodsList()
  },
}
</script>

<style lang="less" scoped>
</style>